import logging
import os

import tornado.ioloop
import tornado.web
from tornado import gen, web, escape, httpclient, websocket
from tornado.auth import GoogleOAuth2Mixin
from tornado.httpserver import HTTPServer
from tornado.options import define, options


class BaseHandler(tornado.web.RequestHandler):
    def get_current_user(self):
        return self.get_secure_cookie("user")


class MainHandler(BaseHandler):
    def get(self):
        if not self.current_user:
            self.redirect("/login")
            return
        name = tornado.escape.xhtml_escape(self.current_user)
        self.write("Hello, " + name)


class ClearHandler(web.RequestHandler):
    @web.authenticated
    def get(self):
        logging.info("清除cookie4")
        self.clear_all_cookies()
        self.write("清除cookie4")


class GoogleOAuth2LoginHandler(tornado.web.RequestHandler,
                               GoogleOAuth2Mixin):
    @tornado.gen.coroutine
    def get(self):
        if self.get_argument('code', False):
            user = yield self.get_authenticated_user(
                redirect_uri='http://your.site.com/auth/google',
                code=self.get_argument('code'))
            # Save the user with e.g. set_secure_cookie
        else:
            yield self.authorize_redirect(
                redirect_uri='http://your.site.com/auth/google',
                client_id=self.settings['google_oauth']['key'],
                scope=['profile', 'email'],
                response_type='code',
                extra_params={'approval_prompt': 'auto'})


class LoginHandler(BaseHandler):
    def get(self):
        self.render("login.html")

    def post(self):
        self.set_secure_cookie("user", self.get_argument("name"), None)
        self.redirect("/")


class AyncHandler(web.RequestHandler):

    @gen.coroutine
    def get(self):
        http = httpclient.AsyncHTTPClient()
        try:
            response = yield http.fetch("http://192.168.133.163:8601/api/nledu-iotbd-system-core/datadic/all")
            json = escape.json_decode(response.body)
            self.write("Fetched " + str(json))
        except BaseException as b:
            self.write("出错了" + b)


class WebsosketHandler(BaseHandler):
    def get(self):
        self.render("websocket.html")


class EchoWebSocket(websocket.WebSocketHandler):
    def open(self):
        print("WebSocket opened")

    def on_message(self, message):
        logging.info("收到的消息%s" % message)
        self.write_message(u"You said: " + message)

    def on_close(self):
        print("WebSocket closed")


setting = dict(
    cookie_secret="Q7Hcm7meQreye+jDU6rs87OJR+L3a0Omu7inkPppTRg=",
    debug=True,
    autoreload=True,
    login_url="/login",
    xsrf_cookies=True,
)


# 格式化日志输出格式
# 默认是这种的：[I 160807 09:27:17 web:1971] 200 GET / (::1) 7.00ms
# 格式化成这种的：[2016-08-07 09:38:01 执行文件名:执行函数名:执行行数 日志等级] 内容消息
class LogFormatter(tornado.log.LogFormatter):
    def __init__(self):
        super(LogFormatter, self).__init__(
            fmt='%(color)s[%(asctime)s %(filename)s:%(funcName)s:%(lineno)d %(levelname)s]%(end_color)s %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )


def make_app():
    tornado.options.parse_command_line()
    return tornado.web.Application([
        (r"/", MainHandler),
        (r"/async", AyncHandler),
        (r"/clean", ClearHandler),
        (r"/login", LoginHandler),
        (r"/websocket", EchoWebSocket),
        (r"/showwebsocket", WebsosketHandler),
    ], **setting)


def main():
    # options.log_file_prefix = os.path.join(os.path.dirname(__file__), 'logs/tornado_main.log')
    [i.setFormatter(LogFormatter()) for i in logging.getLogger().handlers]
    app = make_app()
    server = HTTPServer(app, ssl_options={
        "certfile": os.path.join(os.path.dirname(__file__), "server.crt"),
        "keyfile": os.path.join(os.path.dirname(__file__), "server.key"),
    })
    server.listen(8888)
    tornado.ioloop.IOLoop.current().start()


if __name__ == "__main__":
    main()
